import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

const extraAllowedHosts =
  process.env.VITE_ALLOWED_HOSTS?.split(',').map((host) => host.trim()).filter(Boolean) ?? []

const disableHmr = process.env.VITE_DISABLE_HMR === 'true'
const hmrHost = process.env.VITE_HMR_HOST?.trim()
const hmrProtocol = process.env.VITE_HMR_PROTOCOL?.trim()
const hmrPort = process.env.VITE_HMR_PORT?.trim()
const hmrClientPort = process.env.VITE_HMR_CLIENT_PORT?.trim()

const buildHmrConfig = () => {
  if (disableHmr) {
    return false
  }
  const config = {}
  if (hmrHost) config.host = hmrHost
  if (hmrProtocol) config.protocol = hmrProtocol
  if (hmrPort) config.port = Number(hmrPort)
  if (hmrClientPort) config.clientPort = Number(hmrClientPort)
  return config
}

const allowedHosts = Array.from(
  new Set([
    'localhost',
    '127.0.0.1',
    'n6b6a9ee.natappfree.cc',
    '6652cd12.r19.cpolar.top',
    '233d381a.r19.cpolar.top',
    ...extraAllowedHosts,
  ])
)

const allowedHostPatterns = [/\.natappfree\.cc$/, /\.cpolar\.top$/]

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueDevTools(),
  ],
  server: {
    host: process.env.VITE_DEV_HOST || '0.0.0.0',
    port: 5176,
    cors: true,
    allowedHosts: [...allowedHosts, ...allowedHostPatterns],
    hmr: buildHmrConfig(),
  },
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
})
